import React, { Component } from 'react';
import { NavBar, Icon, InputItem, List, Switch, Toast } from 'antd-mobile';
import * as addressApi from '../../api/address';

export default class create extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            mobile: '',
            address: '',
            is_default: false,
        };
    }

    async handleSubmit() {
        // ...
        console.log(this.state);
        const data = {
            ...this.state,
            is_default: this.state.is_default ? 1 : 0,
        };
        const res = await addressApi.save(data);
        // 添加失败，给予提示
        if (res.code !== 201) {
            Toast.fail(res.message);
            return;
        }
        // 添加成功，返回列表页面
        this.props.history.goBack();
    }

    render() {
        return (
            <div className="address-create-page">
                <NavBar
                    mode="dark"
                    icon={
                        <Icon
                            type="left"
                            onClick={() => this.props.history.goBack()}
                        />
                    }
                    rightContent={[
                        <span key="save" onClick={() => this.handleSubmit()}>
                            保存地址
                        </span>,
                    ]}
                >
                    地址管理
                </NavBar>

                <InputItem onChange={(name) => this.setState({ name })}>
                    收货人姓名
                </InputItem>
                <InputItem onChange={(mobile) => this.setState({ mobile })}>
                    收货人手机号
                </InputItem>
                <InputItem onChange={(address) => this.setState({ address })}>
                    收货人地址
                </InputItem>

                <List>
                    <List.Item
                        extra={
                            <Switch
                                checked={this.state.is_default}
                                onChange={() => {
                                    this.setState({
                                        is_default: !this.state.is_default,
                                    });
                                }}
                            />
                        }
                    >
                        是否默认收货地址
                    </List.Item>
                </List>
            </div>
        );
    }
}
